package dao;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.List;

import order_cancel_subscription.SqlProcessor;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import persistence.CostUnit;
import persistence.CostUnitDAO;
import persistence.DAOFactory;
import persistence.DAOFactoryJdbcTestImpl;
import persistence.LibraryLocation;
import persistence.LibraryLocationDAO;
import persistence.exception.DAOException;
import persistence.util.TestConnectionProvider;

public class CostUnitDAOTest {
	
	private static CostUnitDAO costUnitDAO;
	private static LibraryLocationDAO libLocationDAO;
	private static SqlProcessor sqlProcessor;
	private Boolean changedDB = Boolean.FALSE;
	
	@BeforeClass
	public static void initializeTests() throws DAOException {
		System.out.println("Starting BEFORE CLASS");
		sqlProcessor = new SqlProcessor(
							new TestConnectionProvider());
		
		DAOFactory factory = new DAOFactoryJdbcTestImpl();
		costUnitDAO = factory.getCostUnitDAO();
		libLocationDAO = factory.getLibraryLocationDAO();
		initDB();
		System.out.println("Finishing BEFORE CLASS");
	}
	
	@Test
	public void find() throws DAOException {
		CostUnit costUnit = costUnitDAO.find(2);
		LibraryLocation location = libLocationDAO.find(1);
		
		assertEquals(costUnit.getName(), "SAM");
		assertEquals(costUnit.getLocation(), location);
	}
	
	@Test
	public void findAll() throws DAOException {
		List<CostUnit> costUnits = costUnitDAO.findAll();
		assertTrue(costUnits.size()==3);
	}
	
	@Test
	public void findAllByTitle() throws DAOException {
		List<CostUnit> costUnits = costUnitDAO.findAllByTitle("");
		List<CostUnit> allCostUnits = costUnitDAO.findAll();		
		assertTrue(costUnits.size()==allCostUnits.size());		
		
		List<CostUnit> costUnitsWithI = costUnitDAO.findAllByTitle("I");
		assertTrue(costUnitsWithI.size()==1);
	}
	
	@Test
	public void findAllForLocation() throws DAOException {
		
	}
	
	@Test
	public void updateCostUnit() throws DAOException {
		
	}	
	
	@After
	public void tearDown() {
		if (changedDB) {
			sqlProcessor.executeSqlScript("scripts/db_schema_hsqldb.sql");
			sqlProcessor.executeSqlScript("scripts/test_data_hsqldb.sql");
			changedDB = Boolean.FALSE;
			System.out.println("AFTER");
		}
	}
	
	@AfterClass
	public static void restoreDBstate() {
		System.out.println("Starting AFTER CLASS");
		restoreDB();
		System.out.println("Finishing AFTER CLASS");
	}
	
	protected static void initDB() {
		if(sqlProcessor==null)
			System.out.println("SQL PROCESS IS NULL!");
		sqlProcessor.executeSqlScript("scripts/db_schema_hsqldb.sql");
		sqlProcessor.executeSqlScript("scripts/test_data_hsqldb.sql");
	}
	
	protected static void restoreDB() {
		initDB();
	}
}
